(function (angular) {
    'use strict';
    angular.module("fs.authorization").directive('fsPermission', fsPermission);
    fsPermission.$inject = ['$log'];
    function fsPermission($log) {
        return {
            restrict: 'A',
            scope: false,
            link: function ($scope, $element, $attrs, ctrls, $transclude) {
                var log = $log.getInstance('permission'), permissions, i;
                $scope.$watch($attrs.fsPermission, function (permissionConfig) {
                    $scope.permissionConfig = permissionConfig;
                    authorize();
                });
                function authorize(event) {
                    if (!permissions) {
                        permissions = $scope.permissionConfig ? ($scope.permissionConfig.permission || '*') : '*';
                        if (permissions == '*')
                            return;
                        permissions = permissions.split(',');
                        angular.forEach(permissions, function (value, key) {
                            permissions[key] = value.trim();
                        });
                        for (i = 0; i < permissions.length; i++) {
                            if (!$scope.permissionConfig || ($scope.permissionConfig.authorization && $scope.permissionConfig.authorization[permissions[i]])) {
                                return;
                            }
                        }
                        if (i >= permissions.length) {
                            $element.remove();
                        }
                    }
                }
            }
        };
    }
})(angular);